<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            width: 140px;
            margin: 100px auto;
        }
        
        button {
            display: inline-block;
        }
        
        span {
            display: inline-block;
            width: 30px;
            height: 30px;
            color: #fff;
            font-size: 16px;
            background-color: black;
            text-align: center;
            line-height: 30px;
        }
    </style>

    <script>
        window.addEventListener('load', function() {

            // setInterval(回调函数, 间隔的毫秒数) 使用基本与setTimeout一致
            // setTimeout 与 setInterval的区别
            // setTimeout()只会执行一次
            // setInterval() 会在每次到达时间间隔时执行
            // setInterval(() => {
            //     console.log('1');
            // }, 1000);

            var hour = document.querySelector('.hour'); // 时
            var miute = document.querySelector('.miute'); // 分
            var second = document.querySelector('.second'); // 秒

            var inputTime = +new Date('2021/09/15 18:00:00') // 输入时间戳
            countDown() // 先调用此次防止第一次刷新页面有空白

            function countDown() {
                var nowTime = +new Date(); // 获取当前时间戳
                var times = (inputTime - nowTime) / 1000; // 剩余时间 秒
                var h = parseInt(times / 60 / 60 % 24);
                var m = parseInt(times / 60 % 60);
                var s = parseInt(times % 60);
                hour.innerHTML = h < 10 ? '0' + h : h;
                miute.innerHTML = m < 10 ? '0' + m : m;
                second.innerHTML = s < 10 ? '0' + s : s;
            }

            var begin = document.querySelector('.begin');
            var stop = document.querySelector('.stop');
            var timer = null;
            // 开启计时器
            begin.addEventListener('click', function() {
                timer = window.setInterval(countDown, 1000);
            });

            // 停止计时器
            stop.addEventListener('click', function() {
                clearInterval(timer);
            });

        });
    </script>
</head>

<body>
    <!-- 例子倒计时 -->
    <div>
        <span class="hour">1</span>
        <span class="miute">2</span>
        <span class="second">3</span>
        <br>
        <br>
        <button class="begin">开始计时</button>
        <button class="stop">停止计时</button>
    </div>
</body>

</html>